import { ActorSystem } from '../actor/actorSystem';
import { PID } from '../actor/pid';
import { Props } from '../actor/props';
import { Process } from '../actor/process';
import { RemoteProcess } from './remoteProcess';
import { RemoteMessageType } from './remote';

interface ActorActivator {
  createInstance(actorId: string): Process;
}

export interface RemoteActivationRequest {
  type: RemoteMessageType.Activation;
  kind: string;
  actorId: string;
  messageId?: string;
  senderPID?: PID;
}

export interface RemoteActivationResponse {
  type: RemoteMessageType.ActivationResponse;
  pid?: PID;
  error?: string;
  messageId?: string;
}

export class RemoteActivator {
  private system: ActorSystem;
  private kinds: Map<string, Props>;

  constructor(system: ActorSystem) {
    this.system = system;
    this.kinds = new Map();
  }

  // 注册可远程激活的 Actor 类型
  register(kind: string, props: Props): void {
    this.kinds.set(kind, props);
  }

  // 取消注册
  unregister(kind: string): void {
    this.kinds.delete(kind);
  }

  // 获取已注册的 Actor 类型
  getKinds(): string[] {
    return Array.from(this.kinds.keys());
  }

  // 激活远程 Actor
  async activate(kind: string, actorId: string): Promise<PID | undefined> {
    const props = this.kinds.get(kind);
    if (!props) {
      return undefined;
    }

    try {
      return props.spawn(this.system, actorId, this.system.root);
    } catch (error) {
      console.error(`Failed to activate actor of kind ${kind}:`, error);
      return undefined;
    }
  }

  // 停止远程 Actor
  async stop(pid: PID): Promise<void> {
    try {
      const process = this.system.processRegistry.get(pid);
      if (process) {
        process.stop(pid);
        this.system.processRegistry.remove(pid);
      }
    } catch (error) {
      console.error(`Failed to stop actor ${pid.id}:`, error);
    }
  }

  // 创建 Actor 实例
  private async createActorInstance(kind: string, props: Props): Promise<Process | null> {
    try {
      const process = props.producer();
      return process;
    } catch (error) {
      console.error(`Failed to create actor instance of kind ${kind}:`, error);
      return null;
    }
  }
}

// 远程激活消息类型
export enum RemoteActivationMessageType {
  ActivationRequest = 'ActivationRequest',
  ActivationResponse = 'ActivationResponse',
  TerminationRequest = 'TerminationRequest',
  TerminationResponse = 'TerminationResponse'
}

// 远程激活请求消息
export interface RemoteActivationRequest {
  type: RemoteActivationMessageType.ActivationRequest;
  kind: string;
  actorId: string;
}

// 远程激活响应消息
export interface RemoteActivationResponse {
  type: RemoteActivationMessageType.ActivationResponse;
  pid?: PID;
  error?: string;
}

// 远程终止请求消息
export interface RemoteTerminationRequest {
  type: RemoteActivationMessageType.TerminationRequest;
  pid: PID;
}

// 远程终止响应消息
export interface RemoteTerminationResponse {
  type: RemoteActivationMessageType.TerminationResponse;
  success: boolean;
  error?: string;
} 